import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:management/const/consts.dart';
import 'package:management/data/network/api/api.dart';
import 'package:management/data/network/entity/demand/response/ListProjectDemandResponse.dart';
import 'package:management/element/loading.dart';
import 'package:management/element/showLogSheet.dart';
import 'package:management/element/toast.dart';
import 'package:management/main.dart';
import 'package:management/page/ModuleProject/project_screen/logic.dart';

import 'state.dart';

class ProjectDetailScreenLogic extends GetxController {
  final ProjectDetailScreenState state = ProjectDetailScreenState();

  @override
  void onInit() {
    super.onInit();
    _initData(false);
  }

  Future<void> refreshProjectDetailPage() async {
    LoadingElement.loadingDialog(true);
    _initData(true);
  }

  void addTask(int index) {
    Get.toNamed(RouteConfig.createDemandScreen,
        arguments: {'demandStatus': index, 'projectId': state.projectId});
  }

  void seeMoreDemand(Records? elementAt) {
    if (elementAt == null) return;
    Get.bottomSheet(
        Wrap(
          children: <Widget>[
            Container(
              padding: const EdgeInsets.symmetric(vertical: 2),
              width: double.infinity,
              height: 60,
              child: TextButton(
                onPressed: () => _deleteDemand(elementAt),
                style: Theme.of(Get.context!).textButtonTheme.style,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      MyText.deleteDemand.tr,
                      style: Theme.of(Get.context!).textTheme.bodyLarge,
                    ),
                  ],
                ),
              ),
            ),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 5),
              width: double.infinity,
              height: 60,
              child: TextButton(
                onPressed: () => Get.back(),
                style: Theme.of(Get.context!).textButtonTheme.style,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      MyText.cancel.tr,
                      style: Theme.of(Get.context!)
                          .textTheme
                          .bodyLarge
                          ?.copyWith(color: MyColor.error),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
        isDismissible: false,
        shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(top: Radius.circular(20))),
        backgroundColor: Theme.of(Get.context!).scaffoldBackgroundColor);
  }

  void _deleteDemand(Records elementAt) {
    Get.back();
    Get.defaultDialog(
        title: MyText.deleteProject.tr,
        titleStyle: Theme.of(Get.context!).textTheme.titleSmall,
        middleText: "${MyText.delete.tr}  ${elementAt.name} ?",
        middleTextStyle: Theme.of(Get.context!).textTheme.bodyLarge,
        onConfirm: () {
          Get.back();
          _realDeleteDemand(elementAt);
        },
        textCancel: MyText.cancel.tr,
        textConfirm: MyText.confirm.tr);
  }

  void _realDeleteDemand(Records elementAt) {
    MyHttpClient.deleteDemandOrTask(elementAt.id.toString()).then((value) {
      if (value.code == 200) {
        refreshProjectDetailPage();
      } else {
        Utils.toastError(value.msg);
      }
    }).onError((error, stackTrace) {
      Utils.toastError(error);
    });
  }

  void seeMore() {
    Get.bottomSheet(
        Wrap(
          children: <Widget>[
            Container(
              padding: const EdgeInsets.symmetric(vertical: 2),
              width: double.infinity,
              height: 60,
              child: TextButton(
                onPressed: () => _conclusionProject(),
                style: Theme.of(Get.context!).textButtonTheme.style,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      state.isConclusion
                          ? MyText.viewProjectResults.tr
                          : MyText.finalProject.tr,
                      style: Theme.of(Get.context!).textTheme.bodyLarge,
                    ),
                  ],
                ),
              ),
            ),
            Container(
              padding: const EdgeInsets.symmetric(vertical: 2),
              width: double.infinity,
              height: 60,
              child: TextButton(
                onPressed: () => _deleteProject(),
                style: Theme.of(Get.context!).textButtonTheme.style,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      MyText.deleteProject.tr,
                      style: Theme.of(Get.context!).textTheme.bodyLarge,
                    ),
                  ],
                ),
              ),
            ),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 5),
              width: double.infinity,
              height: 60,
              child: TextButton(
                onPressed: () => Get.back(),
                style: Theme.of(Get.context!).textButtonTheme.style,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      MyText.cancel.tr,
                      style: Theme.of(Get.context!)
                          .textTheme
                          .bodyLarge
                          ?.copyWith(color: MyColor.error),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
        isDismissible: false,
        shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(top: Radius.circular(20))),
        backgroundColor: Theme.of(Get.context!).scaffoldBackgroundColor);
  }

  void _deleteProject() {
    Get.back();
    Get.defaultDialog(
        title: MyText.deleteProject.tr,
        titleStyle: Theme.of(Get.context!).textTheme.titleSmall,
        middleText: "${MyText.delete.tr}  ${state.projectDetail.value.name} ?",
        middleTextStyle: Theme.of(Get.context!).textTheme.bodyLarge,
        onConfirm: () {
          Get.back();
          _realDelete();
        },
        textCancel: MyText.cancel.tr,
        textConfirm: MyText.confirm.tr);
  }

  void _realDelete() {
    MyHttpClient.deleteProject(state.projectId).then((value) {
      if (value.code == 200) {
        Get.back();
        Get.find<ProjectScreenLogic>().refreshProjectPage();
      } else {
        Utils.toastError(value.msg);
      }
    }).onError((error, stackTrace) {
      Utils.toastError(error);
    });
  }

  void _conclusionProject() {
    Get.back();
    Get.toNamed(RouteConfig.projectConclusionScreen, arguments: {
      'isConclusion': state.isConclusion,
      'projectId': state.projectId
    });
  }

  void jumpToDemandDetail(num? id) {
    if (id == null) return;
    Get.toNamed(RouteConfig.demandOrTaskScreen, arguments: {'demandId': id});
  }

  seeDemandLog(num? id) {
    if (id == null) return;
    MyLogSheet.showLogSheet(id);
  }

  changePriority() {}

  void _initData(bool isRefresh) async {
    await MyHttpClient.getProjectDetail(state.projectId.toString())
        .then((value) {
      if (value.code == 200) {
        state.projectDetail.value = value.data!;
      } else {
        Get.back();
        Utils.toastError(value.msg);
      }
    }).onError((error, stackTrace) {
      Get.back();
      Utils.toastError(error);
    });
    await MyHttpClient.getProjectDemandList(
            state.projectId.toString(), null, null)
        .then((value) {
      if (value.code == 200) {
        state.demandList.value = value.data!;
        for (int i = 0; i < 4; i++) {
          state.listDemandByState[i]?.clear();
          state.listDemandStateCount[i] = 0;
        }
        state.demandList.value.records?.forEach((element) {
          state.listDemandStateCount[element.status?.toInt() ?? 0] =
              (state.listDemandStateCount[element.status?.toInt() ?? 0]! + 1);
          state.listDemandByState[element.status?.toInt() ?? 0]?.add(element);
        });
        state.listDemandStateCount.refresh();
        if (isRefresh) Get.back();
      } else {
        Get.back();
        Utils.toastError(value.msg);
      }
    }).onError((error, stackTrace) {
      Get.back();
      Utils.toastError(error);
    });
    MyHttpClient.getConclusionProject(state.projectId.toString()).then((value) {
      if (value.code == 200) {
        state.isConclusion = value.data == null ? false : true;
      } else {
        Get.back();
        Utils.toastError(value.msg);
      }
    }).onError((error, stackTrace) {
      Get.back();
      Utils.toastError(error);
    });
  }

  getMainColor() {
    return state.listColor[state.projectId % 4];
  }

  String getFinishDay() {
    var now = DateTime.now();
    var end = DateTime.parse(
        state.projectDetail.value.endTime ?? "2001-03-18 06:18:43");
    if (now.isAfter(end)) {
      return '${MyText.xDayLeft.trParams({
            'x': '0'
          })}, ${end.year}-${end.month}-${end.day}';
    }
    var difference = end.difference(now);
    return '${MyText.xDayLeft.trParams({
          'x': difference.inDays.toString()
        })}, ${end.year}-${end.month}-${end.day}';
  }

  double getProgress() {
    if (state.projectDetail.value.totalDemand == null ||
        state.projectDetail.value.finishDemand == null ||
        state.projectDetail.value.totalDemand == 0) {
      return 0;
    }
    return state.projectDetail.value.finishDemand! /
        state.projectDetail.value.totalDemand!;
  }

  getLogo() {
    if (state.projectDetail.value.logoUrl != null &&
        state.projectDetail.value.logoUrl!.isNotEmpty) {
      return NetworkImage(state.projectDetail.value.logoUrl!);
    }
    return AssetImage(state.listBg[(state.projectId + 1) % 4]);
  }

  getBg() {
    if (state.projectDetail.value.backgroundUrl != null &&
        state.projectDetail.value.backgroundUrl!.isNotEmpty) {
      return NetworkImage(state.projectDetail.value.backgroundUrl!);
    }
    return AssetImage(state.listBg[state.projectId % 4]);
  }

  getFlagPriorityColor(num? priority) {
    if (priority == null) return Colors.transparent;
    switch (priority.toInt()) {
      case 0:
        return MyColor.grayScale[200];
      case 1:
        return MyColor.lightBlue;
      case 2:
        return MyColor.lightGreen;
      case 3:
        return MyColor.red;
    }
    return Colors.transparent;
  }
}
